﻿using Forum.BaseController;
using Forum.Service.Interface.NoAuth;

namespace Forum.Controllers.NoAuth
{
    [Route("Api/Login")]
    public class LoginController : NoAuthController<IAuthService>
    {
        public LoginController(IAuthService defaultService, ILogger<NoAuthController<IAuthService>> logger) : base(defaultService, logger)
        {

        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResponse> Login(AuthReq user)
        {
            try
            {
                var token = await DefaultService.LoginAsync(user);
                if (token != null)
                    return ApiResponse.OK("", token);
                else
                    return ApiResponse.Error("用户名或密码错误");
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost("Token")]
        public ApiResponse Token(AuthReq user)
        {
            try
            {
                var token = DefaultService.Token(user);
                if (token != null)
                    return ApiResponse.OK("", token);
                else
                    return ApiResponse.Error("用户名或密码错误");
            }
            catch
            {
                throw;
            }
        }

        [HttpPost("TokenAsync")]
        public async Task<ApiResponse> TokenAsync(AuthReq user)
        {
            try
            {
                var result = await DefaultService.TokenAsync(user);
                if (result != null)
                    return ApiResponse.OK("", result);
                else
                    return ApiResponse.Error("刷新Token异常");
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 刷新token
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost("RefreshToken")]
        public async Task<ApiResponse> RefreshTokenAsync(RefreshTokenReq req)
        {
            try
            {
                var result = await DefaultService.RefreshTokenAsync(req.token, req.refreshToken);
                if (result != null)
                {
                    if (result.Success)
                        return ApiResponse.OK("", result);
                    else
                        return ApiResponse.Error(result.Errors);
                }
                else
                    return ApiResponse.Error("刷新Token异常");
            }
            catch
            {
                throw;
            }
        }
    }
}
